import type { ComponentType, LazyComponent } from "@/framework/vue/types";
import { inject, onUnmounted, ref, type Ref, type VNode } from "vue";

export interface SimpleNavigationInfo {
  path: string;
  name?: string;
  component: ComponentType | LazyComponent;
}

export interface RenderNavigationInfo {
  key: string;
  path: string;
  name?: string;
  component: VNode;
}

export interface SimpleNavigationContext {
  push: (path: string) => Promise<void>;
  replace: (path: string) => Promise<void>;
  pop: (count: number) => void;
  popToTop: () => void;
  back: () => void;
}

export interface SimpleNavigationRef extends SimpleNavigationContext {}

export interface SimpleNavigationCustomHooks {
  onFocus: (fn: () => void) => void;
  removeFocusHandler: (fn: () => void) => void;
  onBlur: (fn: () => void) => void;
  removeBlurHandler: (fn: () => void) => void;
}

/**
 * 获取当前导航上下文
 */
export function useSimpleNavigation(): SimpleNavigationContext {
  return inject<SimpleNavigationContext>("simple-navigation-context")!;
}

/**
 * 在SimpleNavigation导航中,当前所在页面获得焦点时执行钩子(从当前页面返回前面的页面时执行)
 * @param fn
 */
export function useOnFocused(fn: () => void) {
  const hooks = inject<SimpleNavigationCustomHooks>("simple-navigation-item-custom-hooks");
  hooks?.onFocus(fn);
  onUnmounted(() => hooks?.removeFocusHandler(fn));
}

/**
 * 在SimpleNavigation导航中,当前所在页面失去焦点时执行钩子(调用push方法进入新的页面时执行)
 * @param fn
 */
export function useOnBlur(fn: () => void) {
  const hooks = inject<SimpleNavigationCustomHooks>("simple-navigation-item-custom-hooks");
  hooks?.onBlur(fn);
  onUnmounted(() => hooks?.removeBlurHandler(fn));
}

/**
 * 在SimpleNavigation导航中,当前页面是否可见
 */
export function useIsVisible(): Ref<boolean> {
  return inject<Ref<boolean>>("simple-navigation-item-visible") ?? ref(false);
}
